package com.kgo.eidtor.filter;

import cn.hutool.core.util.ObjectUtil;
import com.kgo.eidtor.entity.LoginEntity;
import com.kgo.eidtor.entity.params.JWTParams;
import com.kgo.eidtor.util.JWTTokenUtil;
import org.apache.commons.lang3.StringUtils;
import org.springframework.util.AntPathMatcher;

import javax.servlet.*;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

/**
 * @author keepgoon
 * @Description: TODO
 * @date 2019/3/110:22
 */
public class JWTFilter implements Filter {
    private String loginUrl = "";
    private List<String> ignoreUrl = new ArrayList <>();
    private List<String> ignoreFile = new ArrayList <>();
    private AntPathMatcher utlMatcher = new AntPathMatcher();
    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
        System.out.println("初始化JWT过滤器" +   filterConfig.getInitParameter("ignoreUrl"));

        loginUrl = filterConfig.getInitParameter("loginUrl");
        String _ignoreUrl = filterConfig.getInitParameter("ignoreUrl");
        if (StringUtils.isNotBlank(_ignoreUrl)){
            for(String ignore : _ignoreUrl.split(",")){
                ignoreUrl.add(StringUtils.trimToEmpty(ignore));
            }
        }
        ignoreFile.add(".png");
        ignoreFile.add(".js");
        ignoreFile.add(".ico");
    }

    /**
     * 是否忽略该路径
     * @param path
     * @return
     */
    private boolean isIgnoreURL(String path){
        if (ObjectUtil.isNull(ignoreUrl)||ignoreUrl.isEmpty()|| StringUtils.isBlank(path)){
            return  false;
        }
        for (String ignorPath : ignoreUrl){
            if (utlMatcher.match(ignorPath,path)){
                return true;
            }
        }
        return false;
    }
    private boolean isIgnoreFile(String path){
        if (ObjectUtil.isNull(ignoreFile)||ignoreFile.isEmpty()|| StringUtils.isBlank(path)){
            return  false;
        }
        for (String ignorFile : ignoreFile){
            if (StringUtils.contains(path,ignorFile)){
                return true;
            }
        }
        return false;
    }
    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest httpServletRequest = (HttpServletRequest) servletRequest;
        HttpServletResponse httpServletResponse = (HttpServletResponse) servletResponse;
        System.out.println("登录====过滤器 :  " + httpServletRequest.getRequestURL());
        String contextUri = httpServletRequest.getRequestURI();

        if (isIgnoreFile(contextUri)){
            System.out.println("忽略 文件 ");
            filterChain.doFilter(servletRequest,servletResponse);
            return;
        }
       if (isIgnoreURL(contextUri)){
           System.out.println("忽略  ");
           filterChain.doFilter(servletRequest,servletResponse);
           return;
       }
        //如果头部里面有token就使用头部的token
        String token = httpServletRequest.getHeader(JWTParams.Token);// 从 http 请求头中取出 token
        Cookie[] cookies = httpServletRequest.getCookies();//获取cookie
        /*
            如果头部中没有获取到token，并且请求中的cookie不是空，就遍历cookie
         */
        if (StringUtils.isBlank(token)&& ObjectUtil.isNotNull(cookies)&&cookies.length>0) {
            for (Cookie cookie : cookies) {
                if(StringUtils.equals(cookie.getName(), JWTParams.Token)){
                    token = cookie.getValue();
                }
            }
        }

        if (StringUtils.isNotBlank(token)){
            LoginEntity loginInfo = JWTTokenUtil.verifyToken(token);
            if(loginInfo.getLogin()){
                System.out.println("登录成功"+loginInfo.getUserName());
               // filterChain.doFilter(servletRequest,servletResponse);
                //httpServletResponse.sendRedirect("https://www.baidu.com/");
                filterChain.doFilter(servletRequest,servletResponse);
            }else{
                System.out.println("校验失败");
                httpServletResponse.sendRedirect(loginUrl);
            }
        }else {
            System.out.println("校验失败,无法获取登录 token ");
            httpServletResponse.sendRedirect(loginUrl);

        }
        //重定向
       // httpServletResponse.sendRedirect("");
        return;
    }

    @Override
    public void destroy() {
        System.out.println("销毁JWT过滤器");
    }
}
